package com.example.controller;

import com.example.dto.Response;
import com.example.elasticsearch.data.User;
import com.example.error.ErrorCode;
import com.example.service.ESUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/es/user")
public class ESUserController extends AbstractController {

    @Autowired
    private ESUserService userService;

    @PostMapping("/create")
    public Response<User> createUser(@RequestBody User user) {
        return executeAsync(() -> {
            User savedUser = userService.saveUser(user);
            return Response.success(savedUser);
        });
    }

    @GetMapping("/all")
    public Response<List<User>> getAllUsers(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        return executeAsync(() -> {
            List<User> users = userService.getAllUsers(page, size);
            return Response.success(users);
        });
    }

    @GetMapping("/{id}")
    public Response<User> getUserById(@PathVariable Long id) {
        return executeAsync(() -> {
            Optional<User> user = userService.getUserById(id);
            return user.map(Response::success).orElseGet(() -> Response.failure(ErrorCode.USER_NOT_FOUND));
        });
    }

    @GetMapping("/search")
    public Response<List<User>> findByUsername(@RequestParam String username) {
        return executeAsync(() -> {
            List<User> users = userService.findByUsername(username);
            return Response.success(users);
        });
    }
}
